
import React, { Component } from 'react'
//import fetch from 'isomorphic-fetch'
import CheckboxInput from './CheckboxInput'
import { Link } from 'react-router'
import InputWithLabel from './InputWithLabel'
import TextInput from './TextInput'
import TextareaInput from './TextareaInput'
import SelectInput from './SelectInput'
import NavLink from './NavLink'
import {myAjax, ROOTURL} from './../publicAPI/publicAPI'
import Layers from './Layers'
import style from './addStore.css'


class AddBarber extends Component {
    constructor() {
        super();
        this.state = {
            delete:false,
            deleteId:-1,
            disabled:false,
            status:1,//2修改，1新增

            barberName: "",
            wechatID: "",
            barberPhone: "",
            storeBelong: "",
            select_show: "none",
            errorM: "",
            checkbox1: false,
            checkbox2: false,
            hasBeenMounted: false,  //判断是否已经加载
            addIndex: 0,  //判断是第几个加入的服务

            submitBtn:'block',
            modifyBtn:'none',
            deleteBtn:'none',

            storeData:[],
            storeSelectId:-1

        }


      var URL = ROOTURL +'shop/search.api';

      var _this = this ;
            fetch(URL, {
                method : 'POST',
                mode: 'cors',
                body: JSON.stringify({
                    where: {
                        dd: [['eq', false]],
                        stActivate: [['eq', true]]
                    }
                })
            }).then(res=>{
                if(res.ok){
                    res.json().then(data=>{
                        console.log('--------')
                        console.log(data);
                        console.log(res);
                        console.log('--------')
                        // _this.setState({
                        //    storeData:data
                        // })
                        // alert(this.state.storeData.length);
                        for(var i=0;i<data.length;i++){
                          this.state.storeData.push(<li data-id={data[i].id} onClick={(e) => this.inputTClick(e)}>{data[i].dname}</li>)
                        }
                    })
                }
            })

    }


    componentWillMount() {
        console.log("将安装", this.props.params.id);


        if (this.props.params.id != undefined) {
            //    根据参数获取数据

            console.log('-----',this.props.params.id);
            this.setState({
              disabled:true,
              submitBtn:'none',
              modifyBtn:'block',
              deleteBtn:'block',

            });

            if (!this.state.hasBeenMounted && this.props.params.id){
                console.log('set finished');
                this.handleGetInfo();
            }
        }else{
            this.setState({
              disabled:false,
              submitBtn:'block',
              modifyBtn:'none',
              deleteBtn:'none',

            });
        }
    }

    componentDidMount() {

    }

    handleGetInfo(){
            var url = ROOTURL + 'servant/profile/instance.api';
            var _this = this;
            var param= {
                id:this.props.params.id
            }
            fetch(url,{
                method: 'post',
                headers: {
                  "Content-type": "application/json; charset=UTF-8"
                },
                body: JSON.stringify(param)

            }).then(res=>{
                if(res.ok){
                    res.json().then(data=>{
                        console.log(data);
                            _this.setState({
                                barberName: data.meta.name,
                                wechatID: data.userid,
                                barberPhone: data.meta.phone,
                                storeBelong: data.meta.shop,
                                checkbox1: data.meta.isUse,
                                checkbox2: data.meta.isAssigned
                                //checkbox8 : data.stActivate,


                                //servicePhone : data.meta.phone,


                                //description : data.meta.description,


                                //imgHash : data.meta.hashed


                            })
                        console.log(_this.state)
                    })
                }
            })
        }

    getOptions(data){
        var options = [];
        options.push(data.map((e,index)=><option key={index} value={e}>{e}</option>));
        return options;
    }

    inputFocus() {
        this.setState({select_show: "block"})
    }

    inputTClick(e) {
        const selectValue = e.target.innerText
        console.warn(e.target.getAttribute('data-id'));
        this.setState({
          storeSelectId: e.target.getAttribute('data-id')
        })

        this.setState({select_show: "none", storeBelong: selectValue})

    }

    handleModify(e){
        this.setState({
          disabled:false,
          submitBtn:'block',
          modifyBtn:'none',
          deleteBtn:'none',
          status:2
        });
    }

    handleDelete(id){

       this.setState({
          delete:true,
          deleteId:id
       })
    }

    deleteBarber(){
            var _this = this;
            var param = {
              // id:this.state.deleteId
            }
               var URL1 = ROOTURL + 'barber/profile/instance.api?id=' + this.state.deleteId;
               // alert(this.state.deleteId);
               fetch(URL1,{
                   method: 'DELETE',
                   headers: {
                        "Content-type": "application/json; charset=UTF-8"
                    },
                   body: param
               }).then(function (res) {
                   if (res.ok){
                       console.log('delete success');
                       window.location.href="/BarberM";
                   }else{
                       console.log(res)
                   }
               });
               this.setState({
                   delete: !this.state.delete
               });
    }

    handleSubmit(e){

        if(this.state.barberName==""){
           this.setState({errorM: "请输入理发师姓名！"});
        }else{
            if(this.state.status == 1){
                this.setState({errorM: ""});
                var data = {
                    // "userid" : this.state.wechatID,
                    // "barber" : this.state.barberName,
                    // "shop" : this.state.storeBelong,
                    // "stActivate" :this.state.checkbox2
                };
                var _servant = 0;
                data.dname = this.state.barberName;
                data.dd = false;
                const  newUrl = ROOTURL + 'user/barber/instance.api';
                fetch(newUrl, {
                    method: 'post',
                    headers: {
                      "Content-type": "application/json; charset=UTF-8"
                    },
                    body: JSON.stringify(data)
                  }).then(res=>{
                    if(res.ok){
                        res.json().then(_data=>{

                            _servant = _data.id;
                            console.log(_servant);

                            const URL = ROOTURL +'servant/profile/instance.api'
                             var param = {

                             };
                             param.servant = _servant;
                             // console.log('---------------------------------------------');
                             // console.log(_servant);
                             // console.log('---------------------------------------------');
                             param.dd = false;
                             param.shop = this.state.storeSelectId;
                             param.userid = this.state.wechatID;
                             param.stActivate = true;
                             param.meta =  {
                                name: this.state.barberName,
                                shop: this.state.storeBelong,
                                phone: this.state.barberPhone,
                                isUse: this.state.checkbox1,
                                isAssigned: this.state.checkbox2
                             }
                             fetch(URL, {
                                 method: 'post',
                                 mode : 'no-cors',
                                 headers: {
                                    "Content-type": "application/json; charset=UTF-8"
                                 },
                                 body: JSON.stringify(param)
                               })
                               .then(function (data) {
                                  alert('保存成功！');
                                  window.location.href = '/BarberM'
                               })
                               .catch(function (error) {
                                  console.log('Request failed', error);
                               });

                        })
                    }else{

                    }
                  })
              }else if(this.state.status == 2){
                  const URL = ROOTURL +'servant/profile/instance.api'
                   var param = {

                   };
                   param.id = this.props.params.id;
                   param.dd = false;
                   if(this.state.storeSelectId!=(-1)){
                      param.shop = this.state.storeSelectId;
                   }

                   param.userid = this.state.wechatID;
                   param.stActivate = true;
                   param.meta =  {
                      name: this.state.barberName,
                      shop: this.state.storeBelong,
                      phone: this.state.barberPhone,
                      isUse: this.state.checkbox1,
                      isAssigned: this.state.checkbox2
                   }
                   // alert(JSON.stringify(param));
                   fetch(URL, {
                       method: 'post',
                       mode : 'no-cors',
                       headers: {
                          "Content-type": "application/json; charset=UTF-8"
                       },
                       body: JSON.stringify(param)
                     })
                     .then(function (data) {

                        alert('修改成功！');
                        window.location.href = '/BarberM'
                     })
                     .catch(function (error) {
                        console.log('Request failed', error);
                     });
              }



        }


    }

    render() {



        console.log("添加理发师");
        console.log(this.state);
        return (
            <div className="right-wrap">
                <div className="wrap" style={{paddingBottom:"40px"}}>
                    <div className={style["input_div"]}>
                        <label>姓名</label>
                        <TextInput inputId="barberName"  disabled={this.state.disabled}  val={this.state.barberName} onChange={val=>this.setState(Object.assign({}, this.state, {barberName: val}))}/>&nbsp;&nbsp;
                         <span style={{marginBottom:'20px',marginLeft:'2px',color:'red'}}>{this.state.errorM}</span>
                    </div>

                    <div className={style["input_div"]}>
                        <label>微信id</label>
                        <TextInput inputId="wechatID" disabled={this.state.disabled}  val={this.state.wechatID} onChange={val=>this.setState(Object.assign({}, this.state, {wechatID: val}))}/>
                    </div>

                    <div className={style["input_div"]}>
                        <label>手机号码</label>
                        <TextInput inputId="barberPhone"  disabled={this.state.disabled}  val={this.state.barberPhone} onChange={val=>this.setState(Object.assign({}, this.state, {barberPhone: val}))}/>
                    </div>
                    <div className={style["input_div"]} style={{position:'relative'}}>
                        <label>所属门店</label>
                        <input inputId="storeBelong" disabled={this.state.disabled} className="default-text"  value={this.state.storeBelong} readOnly onFocus={() => this.inputFocus()} onChange={val=>this.setState(Object.assign({},this.state, {storeBelong: val}))}/>
                        <ul  className="input_select" style={{display: this.state.select_show}}>

                         {this.state.storeData}


                        </ul>
                    </div>
                    <div className={style["input_div"]} style={{display:'none'}}>
                        <label>理发师</label>
                    </div>

                    <div className="checkbox_div" style={{marginTop:'18px',marginBottom:'20px'}}>
                        <CheckboxInput id="enabled" disabled={this.state.disabled} isCheck={this.state.checkbox1} onChange={val=>this.setState(Object.assign({}, this.state, {checkbox1: val}))}/>
                        <label htmlFor="enabled">启用</label>
                    </div>

                    <div className="checkbox_div" style={{marginTop:'10px',marginBottom:'20px'}}>
                        <CheckboxInput id="enabled" disabled={this.state.disabled} isCheck={this.state.checkbox2} onChange={val=>this.setState(Object.assign({}, this.state, {checkbox2: val}))}/>
                        <label htmlFor="enabled">是否分配工作（关闭时，计算门店可用服务量时不将其计算在内, 且不为其分配工作）</label>
                    </div>

                    <span id="hint"/>
                    <button id="submit" className={style["main_btn"]} onClick={(e) => this.handleSubmit(e) }  style={{backgroundColor: '#2285c7',float:'left',border: '1px solid #1e77b3',display: this.state.submitBtn}}>保存</button>
                    <button id="modify" className={style["main_btn"]} style={{backgroundColor: '#2285c7',float:'left',border: '1px solid #1e77b3',display: this.state.modifyBtn,marginLeft:'12px'} } onClick={  (e) => this.handleModify(e) }>修改</button>
                    <button id="delete" className={style["main_btn"]} style={{backgroundColor: '#f2846f',float:'left',border: '1px solid #d55c44',display: this.state.deleteBtn,marginLeft:'12px'} } onClick={ (e) =>this.handleDelete(this.props.params.id) }>删除</button>

                    <Link to={`/BarberM`}>
                           <button id="back" className={style["main_btn"]}  style={{backgroundColor: '#2285c7',border: '1px solid #1e77b3',marginLeft:'12px'}}>返回</button>
                    </Link>
                </div>
                { this.state.delete ?
                  <div id={style.msgDialog}>
                    <div className={style['msgDialog_div']}><h3 id={style['msgDialog_title']}>删除提示？</h3><p id={style['msgDialog_content']}>确认删除？</p>
                      <div className={style['msgDialog_button']}>
                        <button id={style['msgDialog_yes']} onClick={this.deleteBarber.bind(this)}>确定</button>
                        <button id={style['msgDialog_no']} onClick={()=>this.setState({delete: !this.state.delete})}>取消</button>
                      </div>
                    </div>
                  </div> : null}
            </div>
        )
    }
}
export default AddBarber
